#include "BaseType.h"
#include "Tracer.h"
#include "FileUtil.h"
#include "StrUtil.h"
#include <sys/types.h>
#include <signal.h>

using namespace libemb;

int main(int argc,char** argv)
{
    //Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	//Tracer::getInstance().addSink(std::make_shared<STDSink>()).start();
    if (argc!=2) 
    {
        return -1;
    }
    std::string procName(argv[1]);
    if (procName.empty()) 
    {
        return -1;
    }

    Directory dir;
    if(!dir.enterDir("/proc"))
    {
        return -1;
    }
    std::vector<std::string> pathList = dir.getFileList();
    for(int i=0; i<pathList.size(); i++) 
    {
        std::string fullPath = "/proc/";
        fullPath += pathList[i];
        if (!File::exists(CSTR(fullPath)))
        {
            //TRACE_DBG("not exsit:%s",CSTR(fullPath));
            continue;
        }
        if(!StrUtil::isIntString(CSTR(pathList[i])))
        {
            continue;
        }
        int pid = StrUtil::stringToInt(pathList[i]);
        if (pid<=1) 
        {
            //TRACE_DBG("pid error:%d",pid);
            continue;
        }
        File file;
        std::string procStatusFileName = fullPath + "/status"; 
        if (!file.open(CSTR(procStatusFileName), IO_MODE_RD_ONLY))
        {
            //TRACE_DBG("cannot open:%s",CSTR(procStatusFileName));
            continue;
        }
        std::string line;
        if(file.readLine(line)<=0)/* 读取第一行: "Name:   xxx" */
        {
            //TRACE_DBG("read line error:%s",CSTR(line));
            continue;
        }
        if (line.substr(0,5)!="Name:")
        {
            //TRACE_DBG("substr line error:%s",CSTR(line));
            continue;
        }
        std::string name = StrUtil::trimTailBlank(line.substr(5));
        if(name!=procName)
        {
            //TRACE_DBG("proc name error:%s != %s ",CSTR(name),CSTR(procName));
            continue;
        }
        return kill(pid,9);
    }
    printf("%s: No such proccess!",CSTR(procName));
    return 0;
}
